<template>
  <div class="notification-center">
    <div class="page-header">
      <h2>消息通知</h2>
      <p class="subtitle">查看系统推送的重要通知和消息</p>
    </div>

    <el-card shadow="never" class="notification-card">
      <template #header>
        <div class="card-header">
          <span>消息列表</span>
          <div class="filter-actions">
            <el-select v-model="filterType" placeholder="消息类型" clearable @change="handleFilterChange" style="width: 180px">
              <el-option label="全部" value="" />
              <el-option label="协商完成" value="NEGOTIATION_COMPLETED" />
              <el-option label="排期取消" value="SCHEDULE_CANCELED" />
              <el-option label="系统通知" value="SYSTEM_NOTIFICATION" />
            </el-select>
            <el-select v-model="readStatus" placeholder="阅读状态" clearable @change="handleFilterChange" style="width: 180px">
              <el-option label="全部" value="" />
              <el-option label="未读" value="0" />
              <el-option label="已读" value="1" />
            </el-select>
            <el-button type="primary" @click="markAllAsRead" :disabled="unreadCount === 0">
              全部标为已读
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="notification-list" v-loading="loading">
        <el-empty description="暂无消息通知" v-if="notifications.length === 0 && !loading" />
        
        <div
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': !notification.read }"
          @click="viewNotificationDetail(notification)"
        >
          <div class="notification-header">
            <div class="notification-title">
              <el-tag :type="getNotificationTypeTag(notification.type)" size="small">
                {{ getNotificationTypeText(notification.type) }}
              </el-tag>
              <span>{{ notification.title }}</span>
            </div>
            <div class="notification-time">
              {{ formatDateTime(notification.createdTime) }}
            </div>
          </div>
          
          <div class="notification-content">
            {{ notification.content }}
          </div>
          
          <div class="notification-footer">
            <div class="read-status">
              <el-tag v-if="!notification.read" size="small" effect="plain" type="danger">未读</el-tag>
              <el-tag v-else size="small" effect="plain" type="info">已读</el-tag>
            </div>
            <div class="notification-actions">
              <el-button 
                type="primary" 
                link 
                size="small" 
                @click.stop="markAsRead(notification)" 
                v-if="!notification.read"
              >
                标为已读
              </el-button>
              <!-- <el-button 
                v-if="notification.targetUrl" 
                type="primary" 
                link 
                size="small" 
                @click.stop="navigateToTarget(notification)"
              >
                查看详情
              </el-button> -->
              <el-button 
                type="danger" 
                link 
                size="small" 
                @click.stop="deleteNotification(notification)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :layout="'total, sizes, prev, pager, next'"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentNotification?.title || '消息详情'"
      width="500px"
    >
      <div class="notification-detail">
        <div class="detail-header">
          <el-tag :type="getNotificationTypeTag(currentNotification?.type)" size="small">
            {{ getNotificationTypeText(currentNotification?.type) }}
          </el-tag>
          <span class="detail-time">{{ formatDateTime(currentNotification?.createdTime) }}</span>
        </div>
        
        <div class="detail-content">
          {{ currentNotification?.content }}
        </div>
        
        <div class="detail-footer" v-if="currentNotification?.targetUrl">
          <el-button type="primary" @click="navigateToTarget(currentNotification)">
            查看相关页面
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getNotifications, 
  markAsRead as apiMarkAsRead, 
  markAllAsRead as apiMarkAllAsRead,
  deleteNotification as apiDeleteNotification
} from '@/api/notification';

// 路由
const router = useRouter();

// 状态变量
const loading = ref(false);
const notifications = ref([]);
const currentNotification = ref(null);
const detailDialogVisible = ref(false);
const filterType = ref('');
const readStatus = ref('');

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 计算未读消息数量
const unreadCount = computed(() => {
  return notifications.value.filter(item => !item.read).length;
});

// 初始化数据
onMounted(() => {
  fetchNotifications();
});

// 获取消息通知列表
const fetchNotifications = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      type: filterType.value || null,
      read: readStatus.value || null
    };
    
    const res = await getNotifications(params);
    if (res.data.code === 200) {
      console.log(res.data.data);
      notifications.value = res.data.data.records || [];
      pagination.total = res.data.data.total || 0;
    } else {
      ElMessage.error(res.data.message || '获取消息通知失败');
    }
  } catch (error) {
    console.error('获取消息通知异常:', error);
    ElMessage.error('获取消息通知失败');
  } finally {
    loading.value = false;
  }
};

// 处理筛选变化
const handleFilterChange = () => {
  pagination.current = 1;
  fetchNotifications();
};

// 查看消息详情
const viewNotificationDetail = (notification) => {
  currentNotification.value = notification;
  detailDialogVisible.value = true;
  
  // 如果消息未读，则标记为已读
  if (!notification.read) {
    markAsRead(notification, false);
  }
};

// 标记消息为已读
const markAsRead = async (notification, showMessage = true) => {
  try {
    const res = await apiMarkAsRead(notification.id);
    if (res.data.code === 200) {
      // 更新本地状态
      notification.read = true;
      if (showMessage) {
        ElMessage.success('已标记为已读');
      }
    } else {
      ElMessage.error(res.data.message || '标记已读失败');
    }
  } catch (error) {
    console.error('标记已读异常:', error);
    ElMessage.error('标记已读失败');
  }
};

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    const res = await apiMarkAllAsRead();
    if (res.data.code === 200) {
      // 更新本地状态
      notifications.value.forEach(item => {
        item.read = true;
      });
      ElMessage.success('已将所有消息标记为已读');
    } else {
      ElMessage.error(res.data.message || '标记全部已读失败');
    }
  } catch (error) {
    console.error('标记全部已读异常:', error);
    ElMessage.error('标记全部已读失败');
  }
};

// 删除消息
const deleteNotification = (notification) => {
  ElMessageBox.confirm('确定要删除此消息吗？删除后将无法恢复。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await apiDeleteNotification(notification.id);
      if (res.data.code === 200) {
        ElMessage.success('删除成功');
        // 从列表中移除该消息
        notifications.value = notifications.value.filter(item => item.id !== notification.id);
        // 如果当前正在查看这条消息的详情，关闭详情对话框
        if (currentNotification.value && currentNotification.value.id === notification.id) {
          detailDialogVisible.value = false;
        }
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除消息异常:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 跳转到目标页面
const navigateToTarget = (notification) => {
  if (!notification.targetUrl) return;
  
  // 关闭详情对话框
  detailDialogVisible.value = false;
  
  // 使用路由导航到目标页面
  if (notification.targetUrl.startsWith('http')) {
    // 外部链接
    window.open(notification.targetUrl, '_blank');
  } else {
    // 内部路由路径
    router.push(notification.targetUrl);
  }
  
  // 如果消息未读，标记为已读
  if (!notification.read) {
    markAsRead(notification, false);
  }
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchNotifications();
};

// 处理分页页码变更
const handleCurrentChange = (page) => {
  pagination.current = page;
  fetchNotifications();
};

// 获取消息类型标签样式
const getNotificationTypeTag = (type) => {
  switch (type) {
    case 'NEGOTIATION_COMPLETED': return 'success';
    case 'SCHEDULE_CANCELED': return 'danger';
    case 'SYSTEM_NOTIFICATION': return 'info';
    default: return 'primary';
  }
};

// 获取消息类型文本
const getNotificationTypeText = (type) => {
  switch (type) {
    case 'NEGOTIATION_COMPLETED': return '协商完成';
    case 'SCHEDULE_CANCELED': return '排期取消';
    case 'SYSTEM_NOTIFICATION': return '系统通知';
    default: return '未知类型';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString();
};
</script>

<style scoped>
.notification-center {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.notification-card {
  margin-bottom: 20px;
}

.notification-list {
  min-height: 200px;
}

.notification-item {
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.notification-item:hover {
  border-color: #409EFF;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.notification-item.unread {
  border-left: 4px solid #F56C6C;
  background-color: #fef0f0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-content {
  margin: 10px 0;
  color: #606266;
  line-height: 1.5;
}

.notification-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.notification-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.notification-detail .detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-time {
  font-size: 13px;
  color: #909399;
}

.detail-content {
  margin: 15px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.detail-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-top: 10px;
    width: 100%;
    flex-wrap: wrap;
  }
  
  .notification-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .notification-time {
    margin-top: 5px;
  }
  
  .notification-footer {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .notification-actions {
    margin-top: 10px;
  }
}
</style>